package com.ztsoft.user.utils;

import com.ztsoft.user.pojo.vo.user.Route;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门树结构工具
 */
public class RouteTreeUtils {

    private RouteTreeUtils() {
    }

    /**
     * 构建树
     * 1、数据库查出的部门记录装载在承载部门的列表中
     * 2、构建树（获取根节点，遍历根节点，对每一个根节点构建子树）
     * 3、得到最终树形部门
     *
     * @param routeList 需要拼装的树形层级结构数据集合
     * @return 树形层级结构数据集合
     */
    public static List<Route> buildRouteTree(List<Route> routeList) {
        List<Route> routeTreeParentList = new ArrayList<>();
        List<Route> routeTreeChildrenList = new ArrayList<>();

        // 获取根节点
        routeList.stream().filter(route -> route.getParentId().isEmpty()).forEach(routeTreeParentList::add);
        // 获取子节点（排除调根节点，可防止根节点中的空值引发的空指针异常）
        routeList.stream().filter(route -> !routeTreeParentList.contains(route)).forEach(routeTreeChildrenList::add);
        // 构建子树
        routeTreeParentList.forEach(menuTreeParent -> buildChildren(menuTreeParent, routeTreeChildrenList));
        return routeTreeParentList;
    }

    /**
     * 构建子树
     *
     * @param routeTreeParent       根节点
     * @param routeTreeChildrenList 子节点集合
     * @return 树形层级结构根节点
     */
    public static Route buildChildren(Route routeTreeParent, List<Route> routeTreeChildrenList) {
        List<Route> childrenTree = new ArrayList<>();
        routeTreeChildrenList.stream().filter(route -> route.getParentId().equals(routeTreeParent.getMenuId())).forEach(route -> childrenTree.add(buildChildren(route, routeTreeChildrenList)));
        routeTreeParent.setChildren(childrenTree);
        return routeTreeParent;
    }

}